/**
 * 微信授权认证逻辑
 * @author 明浩 微信: muaiyuese
 */
import { store } from "@/store";
import { clear, setAuth, setUserInfo } from "@/store/reducers/user";
import { ApiGetUserInfo } from "@/api/auth";
import { navigateTo } from "@tarojs/taro";
import { instance as Log } from "@/lib/log";

/**
 * 检查令牌是否有效
 * @returns {boolean} true 有效， false 无效
 */
export const hasAuth = () => {
  const { user } = store.getState();
  const { auth } = user || {};
  if (!auth) {
    return false;
  }
  let expiryTime = 0;
  const nowTime = Date.now();
  let authTime = auth.exipreTime;
  if (authTime) {
    if (typeof authTime === "string") {
      authTime = auth.exipreTime.replace(/-/g, "/");
    }
    const exp = new Date(authTime).getTime();
    expiryTime = exp;
  }
  return expiryTime - nowTime > 300;
};

/**
 * 如果没有令牌先进行登录
 * @param {}
 * @return
 */
export const checkAuth = (
  callback = () => {},
  options?: { backurl?: string; isSwitchTab?: boolean }
) => {
  const { backurl = "", isSwitchTab } = options || {};
  if (hasAuth()) {
    callback();
  } else {
    // Log.log({
    //   url:
    //     "/sub_common/pages/auth/index" +
    //     `?backurl=${encodeURIComponent(backurl)}&isSwitchTab=${
    //       isSwitchTab ? "1" : ""
    //     }`,
    // });
    navigateTo({
      url:
        "/sub_common/pages/auth/index" +
        `?backurl=${encodeURIComponent(backurl)}&isSwitchTab=${
          isSwitchTab ? "1" : ""
        }`,
    });
  }
};

/**
 * 退出登陆
 * @param {}
 * @return
 */
export const loginout = () => {
  store.dispatch(clear());
};

/**
 * 获取用户信息
 * @param {}
 * @return
 */
export const getUserInfo = ({ token, exipreTime, callback }: any = {}) => {
  if (!token) {
    const { user } = store.getState();
    const { auth } = user || {};
    token = auth.token;
    exipreTime = auth.exipreTime;
  } else {
    store.dispatch(setAuth({ token, exipreTime }));
  }
  let userInfo = {};
  ApiGetUserInfo({}).then((res) => {
    if (res.data) {
      userInfo = res.data;
      store.dispatch(setUserInfo(userInfo));
      if (callback) {
        callback();
        return;
      }
    }
  });
};
